import React, { Component, Fragment } from 'react';
import { Form, Input, Select, DatePicker, Button } from 'antd';
import { findDOMNode } from 'react-dom';
import { connect } from 'dva';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import RepairDetail from './RepairDetail';
import moment from 'moment';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import AdSearch from '@/components/AdSearch';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import router from 'umi/router';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { Option } = Select;

@ManageList
@connect(({ repair, loading, component, common }) => ({
  repair,
  loading: loading.effects['repair/repairList'],
  ownCompany: common.ownCompany,
  searchValue: component.searchValue,
  dictObject: common.dictObject,
}))
@Form.create()
export default class RepairList extends Component {
  state = {
    visible: false,
    id: '',
    formValues: {},
    cars: [],
    expandForm: false,
  };
  className = 'RepairList';
  columns = [
    {
      title: '单据号',
      dataIndex: 'repairNo',
      fixed: this.props.isMobile ? false : true,
      render: (text, record) => (
        <AdButton
          mode="a"
          className="repairNo"
          onClick={() => this.showDetail(record.id)}
          text={text}
          code={codes.showDetail}
        />
      ),
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
    },
    //新增start
    {
      title: '保养类型',
      dataIndex: 'upkeepType',
    },
    {
      title: '保养日期',
      dataIndex: 'upkeepTime',
    },
    {
      title: '里程数',
      dataIndex: 'currentMileage',
    },
    {
      title: '送保人',
      dataIndex: 'upkeepPerson',
    },
    {
      title: '应付金额',
      dataIndex: 'totalFee',
      render: text => {
        return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : ''}</span>;
      },
    },
    {
      title: '实付金额',
      dataIndex: 'totalFee1',
      render: text => {
        return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : ''}</span>;
      },
    },
    //新增end
    {
      title: '维修日期',
      dataIndex: 'repairTime',
    },
    {
      title: '送修人',
      dataIndex: 'repairPerson',
    },
    {
      title: '修理厂',
      dataIndex: 'repairFactory',
    },

    {
      title: '币种',
      dataIndex: 'currencyType',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
  ];

  componentDidMount() {
    this.dispatchFun('repair/repairList', {});

    // 查询字典：
    //币种：
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
  }
  componentWillReceiveProps(nextProps) {
    const {
      repair: { repairList },
      dictObject,
    } = nextProps;

    if (dictObject['currency-type'] && repairList.list) {
      dictObject['currency-type'].map(v => {
        repairList.list.map((v1, i1) => {
          if (v.code === v1.currencyType) {
            repairList.list[i1].currencyType = v.value;
          }
        });
      });
    }
  }

  // 分页操作
  handleStandardTableChange = param => {
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.dispatchFun('repair/repairList', params);
  };

  // 重置条件查询表单
  handleFormReset = () => {
    this.setState({ formValues: {}, cars: [] });
    this.dispatchFun('repair/repairList', {});
  };

  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  // 执行条件查询表单
  handleSearch = values => {
    const { repairTime, ...value } = values;
    if (repairTime) {
      value.repairStartTime = moment(repairTime[0]).format(dateFormat);
      value.repairEndTime = moment(repairTime[1]).format(dateFormat);
    }
    const { cars } = this.state;
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      value.vehicleId = vehicleId.join(',');
    } else {
      value.vehicleId = '';
    }
    this.setState({
      formValues: value,
    });
    this.dispatchFun('repair/repairList', value);
  };

  // 跳转 新增页面
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push(`/manageCar/repairList/addrepair`);
  };

  // 跳转 编辑页面
  handleEdit = () => {
    const { id } = this.state;
    this.closeDetail();
    router.push(`/manageCar/repairList/editrepair/${id}`);
  };

  // 关闭右抽屉
  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  // 打开右抽屉
  showDetail = id => {
    this.setState({
      visible: true,
      id,
    });
    this.dispatchFun('repair/repairDetail', { id });
  };

  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch, searchValue } = this.props;
    dispatch({
      type: type,
      payload: params,
      callback: data => {
        let valueList = [];
        data.map(v => {
          const labels = ['updateBy', 'createBy'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: { params: { loginName: v[item] }, url: 'mds/mds-user/selectList' },
                });
            }
          });
        });
      },
    });
  }
  getValue = values => {
    this.setState({
      cars: values,
    });
  };

  render() {
    const {
      form,
      loading,
      ownCompany,
      repair: { repairList, detail },
      match: { params },
      isMobile,
    } = this.props;
    const { id, visible, expandForm } = this.state;
    const { getFieldDecorator } = form;
    // firstForm 参数
    const firstFormItem = (
      <FormItem label="单据号">
        {getFieldDecorator('repairNo')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="维修时间">
        {getFieldDecorator('repairTime')(<RangePicker style={{ width: '100%' }} />)}
      </FormItem>
    );
    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="车牌号">
          {getFieldDecorator('vehicleId')(
            <SearchSelect
              dataUrl="tms/tms-repair/selectVehicle"
              url="tms/tms-repair/selectVehicleView_s" // selectedData只只有id时需要传url
              selectedData={this.state.cars} // 选中值
              multiple={false} // 是否多选
              showValue="cartPlateOneNo"
              searchName="cartPlate"
              columns={columns1} // 表格展示列
              onChange={this.getValue} // 获取选中值
              scrollX={480}
              id="repair_1"
            />
          )}
        </FormItem>,
      ],
      [
        <FormItem label="所属公司">
          {getFieldDecorator('mdsCompanyId')(
            <Select
              allowClear={true}
              showSearch
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
              style={{ width: '100%' }}
            >
              <Option value="">请选择</Option>
              {ownCompany.map((v, i) => {
                return (
                  <Option key={i} value={v.customerCode}>
                    {v.customerName}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };

    const tableButtonsParams = {
      show: false,
      code: codes.add,
      handleAdd: this.handleAdd,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      code: codes.showDetail,
      title: '维修详情',
      closeDetail: this.closeDetail,
      buttons: <AdButton onClick={this.handleEdit} text="编辑" code={codes.edit} />,
    };
    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          disabledRowSelected={true}
          loading={loading}
          data={repairList}
          columns={this.columns}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <RepairDetail isMobile={isMobile} id={id} onClick={this.onClick} />
        </RightDraw>
      </Fragment>
    );
  }
}
